package com.ifkytek.ninegridview;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import jp.wasabeef.glide.transformations.MaskTransformation;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

public class PictureLayout extends LinearLayout {

    private RecyclerView recyclerView;
    private ArrayList<ItemPic> mItems;
    private MyListAdapter mAdapter;
    private int max_size;
    private int addmore_id;
    private int defalut_bg;
    private PictureLayoutListener pictureLayoutListener;

    public void setPictureLayoutListener(PictureLayoutListener pictureLayoutListener) {
        this.pictureLayoutListener = pictureLayoutListener;
    }

    public PictureLayout(Context context) {
        this(context, null);
    }

    public PictureLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public PictureLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PictureLayout);
        defalut_bg = typedArray.getResourceId(R.styleable.PictureLayout_default_bg, R.mipmap.ic_launcher);
        addmore_id = typedArray.getResourceId(R.styleable.PictureLayout_add_more_pic, R.mipmap.ic_launcher_round);

        int column = typedArray.getInteger(R.styleable.PictureLayout_column_size, 3);

        max_size = typedArray.getInteger(R.styleable.PictureLayout_max_choose, 6);
        typedArray.recycle();

        View view = LayoutInflater.from(context).inflate(R.layout.base_recycle, this, true);
        recyclerView = view.findViewById(R.id.rv_list);
        CustomGridLayoutManager gridLayoutManager = new CustomGridLayoutManager(context, column);
        gridLayoutManager.setScrollEnabled(false);
        recyclerView.setLayoutManager(gridLayoutManager);
        mItems = new ArrayList<>();
        ItemPic wrapper = new ItemPic();
        wrapper.setLast(true);
        mItems.add(wrapper);
        mAdapter = new MyListAdapter(R.layout.item_image, mItems);
        recyclerView.setAdapter(mAdapter);
    }


    public void updateMessage(String oldId, ItemPic newitemPic) {
        int position = getMessagePositionById(oldId);
        if (position >= 0) {
            mItems.set(position, newitemPic);
            mAdapter.notifyItemChanged(position);
        }
    }


    public void addMessage(String imageUrl) {
        ItemPic itemPic = new ItemPic();
        itemPic.setUrl(imageUrl);
        addMessageBehind(mItems.get(mItems.size()-1).getItemId(),itemPic);
    }


    public void addMessageBehind(String oldId, ItemPic newPic) {
        int position = getMessagePositionById(oldId);
        if (position >= 0) {
            if (mItems.size() < max_size) {
                mItems.add(position, newPic);
                mAdapter.notifyItemInserted(position);
            } else {
                mItems.set(position, newPic);
                mAdapter.notifyItemChanged(position);
            }
        }
    }

    public void removeMessage(String oldId) {
        int position = getMessagePositionById(oldId);
        if (position >= 0) {
            if (mItems.size() == max_size) {
                mItems.remove(position);
                mAdapter.notifyItemRemoved(position);
                if (!mItems.get(mItems.size() - 1).isLast()) {
                    ItemPic itemPic = new ItemPic();
                    itemPic.setLast(true);
                    mItems.add(itemPic);
                    mAdapter.notifyItemInserted(mItems.size());
                }

            } else {
                mItems.remove(position);
                mAdapter.notifyItemRemoved(position);
            }
        }
    }

    private int getMessagePositionById(String id) {
        for (int i = 0; i < mItems.size(); i++) {
            ItemPic itemPic = mItems.get(i);
            if (itemPic.getItemId().contentEquals(id)) {
                return i;
            }
        }
        return -1;
    }


    private class MyListAdapter extends BaseQuickAdapter<ItemPic, BaseViewHolder> {
        List<ItemPic> mData;

        MyListAdapter(int layoutResId, @Nullable List<ItemPic> data) {
            super(layoutResId, data);
            mData = data;
        }

        @Override
        protected void convert(BaseViewHolder helper, final ItemPic item) {
            SquareImageView imageView = (SquareImageView) helper.itemView.findViewById(R.id.si_image);
            View add_view =  helper.itemView.findViewById(R.id.ic_add);
            //判断是否是最后一条
            if (item.isLast()) {
                add_view.setVisibility(VISIBLE);
            } else {
                add_view.setVisibility(GONE);
                if (item.getUrl()!=null){
                    Glide.with(mContext)
                            .load(item.getUrl())
                            .into(imageView);
                }else{
                    Glide.with(mContext)
                            .load(defalut_bg)
                            .into(imageView);

                }
            }
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //前插入一个图片
                    if (item.isLast()) {
//                        ItemPic itemPic = new ItemPic();
//                        addMessageBehind(item.getItemId(),itemPic);
                        if (pictureLayoutListener != null) {
                            pictureLayoutListener.choosePicture();
                        }
                    } else {
                        removeMessage(item.getItemId());
                    }

                }
            });


        }
    }

    public class ItemPic {

        private boolean isLast;
        private Long itemId;
        private String url;

        public ItemPic() {
            this.itemId = UUID.randomUUID().getLeastSignificantBits();
            this.isLast = false;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public void setLast(boolean last) {
            isLast = last;
        }

        public boolean isLast() {
            return isLast;
        }

        public String getItemId() {
            return itemId.toString();
        }

        public void setItemId(Long itemId) {
            this.itemId = itemId;
        }
    }


    public interface PictureLayoutListener {
        void choosePicture();   //
    }

}
